package com.zerui.manager.app.scheduler.quartz;

import com.zerui.manager.app.scheduler.bean.JobBean;
import com.zerui.manager.app.scheduler.bean.JobLogBean;
import com.zerui.manager.app.scheduler.bean.ScheduleConstants;
import com.zerui.manager.app.scheduler.bean.TaskErrorEvent;
import com.zerui.manager.common.event.SpringEventPublisher;
import com.zerui.manager.common.util.BeanUtils;
import com.zerui.manager.common.util.ExceptionUtils;
import com.zerui.manager.common.util.SpringContextTools;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;


/**
 * 抽象quartz调用
 *
 * @author qianhe
 */
public abstract class AbstractQuartzJob implements Job {

    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobBean jobBean = new JobBean();
        BeanUtils.copyBeanProp(jobBean, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
        try {
            before(context, jobBean);
            if (jobBean != null) {
                doExecute(context, jobBean);
            }
            after(context, jobBean, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, jobBean, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param jobBean 系统计划任务
     */
    protected void before(JobExecutionContext context, JobBean jobBean) {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param jobBean 系统计划任务
     */
    protected void after(JobExecutionContext context, JobBean jobBean, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();
        final JobLogBean sysJobLog = new JobLogBean();
        sysJobLog.setJobName(jobBean.getJobName());
        sysJobLog.setJobGroup(jobBean.getJobGroup());
        sysJobLog.setInvokeTarget(jobBean.getInvokeTarget());
        sysJobLog.setStartTime(startTime);
        sysJobLog.setStopTime(new Date());
        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            SpringEventPublisher myEventPublisher = SpringContextTools.getBean(SpringEventPublisher.class);
            TaskErrorEvent errorEvent = new TaskErrorEvent(this, jobBean, ExceptionUtils.getExceptionMessage(e));
            myEventPublisher.publishEvent(errorEvent);
            sysJobLog.setStatus(ScheduleConstants.FAIL);
            String errorMsg = StringUtils.substring(ExceptionUtils.getExceptionMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus(ScheduleConstants.SUCCESS);
        }
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param jobBean 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, JobBean jobBean) throws Exception;
}
